<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EmptyContent from '../components/EmptyContent.vue';
import SvgIcon from '@/components/SvgIcon/index.vue';

import { useUserStore } from "@/store/modules/user";
import {
  getFollowsListApi,
  followUserApi,
  unfollowUserApi,
  getFansListApi,
} from "@/api/follow";

const userStore = useUserStore();

// 分页参数
const pageParams = ref({
  currentPage: 1,
  pageSize: 10,
  hasMore: true,
  loading: false,
  initialized: false
});

// 粉丝列表数据
const fansList = ref([]);

// 粉丝列表元素引用，用于滚动加载
const fansListRef = ref(null);

// 是否有粉丝
const hasFans = computed(() => {
  return pageParams.value.initialized && fansList.value.length > 0;
});

// 是否为初始加载状态
const isInitialLoading = computed(() => {
  return !pageParams.value.initialized && pageParams.value.loading;
});

// 获取粉丝列表
async function fetchFansList(page = 1, append = false) {
  if ((!pageParams.value.hasMore && page > 1) || pageParams.value.loading) return;

  pageParams.value.loading = true;

  try {
    // 调用真实 API 获取粉丝列表
    const params = {
      page: page,
      limit: pageParams.value.pageSize,
    };
    const response = await getFansListApi(userStore.userInfo.id, params);

    // 处理用户数据
    const fans = (response.items || []).map((fan) => {
      // 根据关注列表判断是否已关注该粉丝
      return {
        ...fan,
        isFollowed: fan.isFollowed || false, // 根据API返回的字段，可能需要调整
        followedDate: fan.followTime || fan.createdAt || new Date().toISOString(),
        activity: fan.lastActive || '最近活跃'
      };
    });

    if (append) {
      // 追加数据
      fansList.value = [...fansList.value, ...fans];
    } else {
      // 替换数据
      fansList.value = fans;
    }

    // console.log("粉丝列表:", fansList.value);

    // 更新分页信息
    pageParams.value.currentPage = response.page || page;
    pageParams.value.hasMore = (response.page < response.totalPages);
    pageParams.value.initialized = true;
  } catch (error) {
    console.error('获取粉丝列表失败:', error);
    ElMessage.error('获取粉丝列表失败，请稍后重试');
  } finally {
    pageParams.value.loading = false;
  }
}

// 监听滚动事件，实现无限加载
function setupScrollListener() {
  // 使用 nextTick 确保 DOM 已更新
  nextTick(() => {
    if (!fansListRef.value) {
      console.error("滚动容器引用未找到");
      return;
    }

    const listElement = fansListRef.value;
    
    // 确保容器可滚动
    if (listElement.scrollHeight <= listElement.clientHeight) {
      console.log("内容不足以滚动，可能需要加载更多");
      if (pageParams.value.hasMore && !pageParams.value.loading) {
        loadMore();
      }
    }
    
    console.log("设置滚动监听器", {
      scrollHeight: listElement.scrollHeight,
      clientHeight: listElement.clientHeight
    });
    
    listElement.addEventListener('scroll', handleScroll);
    
    // 返回清理函数
    return () => {
      console.log("移除滚动监听器");
      listElement.removeEventListener('scroll', handleScroll);
    };
  });
}

// 处理滚动事件（节流版本）
let scrollTimeout = null;
function handleScroll(e) {
  if (scrollTimeout) return;

  scrollTimeout = setTimeout(() => {
    const element = e.target;
    const scrollBottom = element.scrollHeight - element.scrollTop - element.clientHeight;
    
    // console.log("滚动检测", {
    //   scrollTop: element.scrollTop,
    //   scrollHeight: element.scrollHeight,
    //   clientHeight: element.clientHeight,
    //   scrollBottom: scrollBottom
    // });
    
    // 使用更宽松的触发条件
    if (scrollBottom < 200) {
      if (pageParams.value.hasMore && !pageParams.value.loading) {
        console.log("触发加载更多");
        loadMore();
      }
    }
    scrollTimeout = null;
  }, 200);
}

// 加载更多数据
function loadMore() {
  const nextPage = pageParams.value.currentPage + 1;
  fetchFansList(nextPage, true);
}

// 检查是否需要加载更多内容
function checkIfNeedsMoreContent() {
  if (!fansListRef.value) return;
  
  const element = fansListRef.value;
  // 如果内容不足以填满容器，且有更多数据，则加载更多
  if (element.scrollHeight <= element.clientHeight && pageParams.value.hasMore && !pageParams.value.loading) {
    console.log("内容不足以填满容器，自动加载更多");
    loadMore();
  }
}

// 关注粉丝
async function followFan(fan) {
  try {
    // 调用关注API
    await followUserApi(userStore.userInfo.id, fan.id);

    // 更新用户状态
    fan.isFollowed = true;

    // 更新store中的用户数据
    if (userStore.userInfo) {
      const currentFollowingCount = userStore.userInfo.following_count || 0;
      userStore.setUserInfo({
        ...userStore.userInfo,
        following_count: currentFollowingCount + 1
      });
    }

    ElMessage({
      type: 'success',
      message: `已关注 ${fan.username}`
    });
  } catch (error) {
    console.error("关注用户失败:", error);
    ElMessage.error("关注用户失败，请稍后重试");
  }
}

// 取消关注粉丝
async function unfollowFan(fan) {
  ElMessageBox.confirm(`确定要取消关注 ${fan.username} 吗？`, "取消关注", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 调用取消关注 API
        await unfollowUserApi(userStore.userInfo.id, fan.id);

        // 更新用户状态
        fan.isFollowed = false;

        // 更新store中的用户数据
        if (userStore.userInfo) {
          const currentFollowingCount = userStore.userInfo.following_count || 0;
          // 确保不会出现负数
          const newCount = Math.max(0, currentFollowingCount - 1);
          userStore.setUserInfo({
            ...userStore.userInfo,
            following_count: newCount
          });
        }

        ElMessage({
          type: "success",
          message: `已取消关注 ${fan.username}`,
        });
      } catch (error) {
        console.error("取消关注失败:", error);
        ElMessage.error("取消关注失败，请稍后重试");
      }
    })
    .catch(() => {
      // 用户取消，不执行操作
    });
}

// 切换关注状态
function toggleFollow(fan) {
  if (fan.isFollowed) {
    unfollowFan(fan);
  } else {
    followFan(fan);
  }
}

// 格式化关注时间
function formatFollowedTime(timeString) {
  const followedDate = new Date(timeString);
  const now = new Date();
  const diffDays = Math.floor((now - followedDate) / (1000 * 60 * 60 * 24));
  
  if (diffDays === 0) {
    return "今天关注";
  } else if (diffDays === 1) {
    return "昨天关注";
  } else if (diffDays < 30) {
    return `${diffDays}天前关注`;
  } else if (diffDays < 365) {
    const months = Math.floor(diffDays / 30);
    return `${months}个月前关注`;
  } else {
    const years = Math.floor(diffDays / 365);
    return `${years}年前关注`;
  }
}

// 组件挂载时加载初始数据
onMounted(async () => {
  await fetchFansList();
  
  // 设置滚动监听
  const cleanup = setupScrollListener();
  
  // 检查是否需要加载更多内容填满容器
  nextTick(() => {
    checkIfNeedsMoreContent();
  });
  
  // 保存清理函数，在组件卸载时调用
  if (cleanup) {
    onUnmounted(cleanup);
  }
});

// 当列表内容变化时检查是否需要加载更多
watch(fansList, () => {
  nextTick(() => {
    checkIfNeedsMoreContent();
  });
}, { deep: true });
</script>

<template>
  <div class="content-panel">
    <h3>我的粉丝</h3>
    
    <!-- 加载中状态 -->
    <div v-if="isInitialLoading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 有粉丝时显示列表 -->
    <div v-else-if="hasFans" ref="fansListRef" class="fans-list">
      <div v-for="fan in fansList" :key="fan.id" class="user-card">
        <div class="user-avatar">
          <img :src="fan.avatar || 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif'" :alt="fan.username">
          <span v-if="fan.isOfficial" class="official-badge">官方</span>
        </div>
        
        <div class="user-info">
          <div class="user-name-row">
            <h4 class="user-name">{{ fan.username }}</h4>
            <span class="user-type">{{ fan.type || '普通用户' }}</span>
            <span v-if="fan.isMutual" class="mutual-badge">互相关注</span>
          </div>
          
          <p class="user-description">{{ fan.description || '这个人很懒，什么都没有留下' }}</p>
          
          <div class="user-stats">
            <span class="video-count">{{ fan.videoCount || 0 }}个作品</span>
            <span class="follow-time">{{ formatFollowedTime(fan.followedDate) }}</span>
            <!-- <span class="activity-status">{{ fan.activity }}</span> -->
          </div>
        </div>
        
        <div class="user-actions">
          <button 
            class="follow-btn" 
            :class="{ 'following': fan.isFollowed }"
            @click.stop="toggleFollow(fan)"
          >
            {{ fan.isFollowed ? '已关注' : '关注' }}
          </button>
        </div>
      </div>
      
      <!-- 底部加载提示 -->
      <div v-if="pageParams.loading" class="loading-more">
        <div class="loading-spinner small"></div>
        <span>加载更多...</span>
      </div>
      <div v-else-if="!pageParams.hasMore && fansList.length > 0" class="no-more">
        没有更多粉丝了
      </div>
    </div>
    
    <!-- 无粉丝时显示空状态 -->
    <EmptyContent 
      v-else-if="pageParams.initialized" 
      icon="👥" 
      text="暂无粉丝" 
      buttonText="创作视频吸引粉丝" 
      @action="() => {}"
    />
  </div>
</template>

<style scoped lang="scss">
.content-panel {
  display: flex;
  flex-direction: column;
  height: 100%;

  h3 {
    margin-top: 8px;
    margin-bottom: 16px;
    font-weight: 500;
    font-size: 1.4rem;
    color: #ffffff;
    border-left: 4px solid #0096ff;
    padding-left: 12px;
  }

  .loading-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #99a3a7;
  }

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(0, 150, 255, 0.3);
    border-radius: 50%;
    border-top-color: #0096ff;
    animation: spin 1s ease-in-out infinite;
    margin-bottom: 12px;
    
    &.small {
      width: 24px;
      height: 24px;
      border-width: 2px;
      margin-bottom: 0;
      margin-right: 10px;
    }
  }

  .fans-list {
    flex: 1;
    overflow-y: auto;
    max-height: calc(100vh - 120px);
    padding: 0 16px 16px;
    
    .user-card {
      display: flex;
      padding: 16px;
      background-color: #1f2129;
      border-radius: 10px;
      margin-bottom: 12px;
      transition: all 0.2s ease;
      
      &:hover {
        background-color: #272933;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
      }
      
      .user-avatar {
        position: relative;
        width: 50px;
        height: 50px;
        flex-shrink: 0;
        margin-right: 16px;
        
        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
          border: 2px solid #3a3d4a;
        }
        
        .official-badge {
          position: absolute;
          bottom: -2px;
          right: -2px;
          background-color: #ff9500;
          color: #fff;
          font-size: 0.65rem;
          padding: 1px 4px;
          border-radius: 4px;
          font-weight: bold;
        }
      }
      
      .user-info {
        flex: 1;
        overflow: hidden;
        
        .user-name-row {
          display: flex;
          align-items: center;
          margin-bottom: 6px;
          
          .user-name {
            margin: 0;
            font-size: 1.1rem;
            color: #ffffff;
            font-weight: 500;
          }
          
          .user-type {
            margin-left: 8px;
            font-size: 0.75rem;
            color: #99a3a7;
            background-color: rgba(153, 163, 167, 0.1);
            padding: 1px 6px;
            border-radius: 4px;
          }
          
          .mutual-badge {
            margin-left: 8px;
            font-size: 0.75rem;
            color: #0096ff;
            background-color: rgba(0, 150, 255, 0.1);
            padding: 1px 6px;
            border-radius: 4px;
          }
        }
        
        .user-description {
          margin: 0;
          font-size: 0.9rem;
          color: #99a3a7;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-bottom: 8px;
        }
        
        .user-stats {
          display: flex;
          font-size: 0.85rem;
          color: #6c7a83;
          gap: 16px;
          
          .video-count, .follow-time, .activity-status {
            display: inline-block;
          }
          
          .activity-status {
            color: #0096ff;
          }
        }
      }
      
      .user-actions {
        display: flex;
        align-items: center;
        
        .follow-btn {
          height: 32px;
          padding: 0 16px;
          font-size: 0.9rem;
          cursor: pointer;
          transition: all 0.2s ease;
          border-radius: 4px;
          
          background-color: #0096ff;
          border: none;
          color: white;
          
          &:hover {
            background-color: #0084e0;
          }
          
          &.following {
            background-color: transparent;
            border: 1px solid #99a3a7;
            color: #99a3a7;
            
            &:hover {
              color: #ff4949;
              border-color: #ff4949;
            }
          }
        }
      }
    }
  }
  
  .loading-more, .no-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 16px;
    color: #99a3a7;
    font-size: 0.9rem;
  }
  
  .no-more {
    color: #6c7a83;
    margin-top: 8px;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>